<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/22 0022
 * Time: 10:10
 */

namespace app\admin\controller;


use think\Controller;
use think\Config;
use think\Loader;
use think\Db;

class GoodscateController extends BaseController
{
    /*
     * 列表页
     */
    public function index(){
        if (request()->isAjax()){
            $data=Db::name("goods_cate")->field("id,pid,cate_name as title,sort")->order("sort ASC")->select();
            $result["data"]=$data;
            $result["code"]=1;
            return json($result);
        }
        return $this->fetch("index");
    }

    /*
     * 添加
     */
    public function add(){
        if(request()->isPost()){
            $list["pid"]=input("param.pid");
            $list["cate_name"]=input("param.cate_name");
            $list["sort"]=input("param.sort");
            $find=Db::name("goods_cate")->where(["cate_name"=>$list["cate_name"]])->find();
            if ($find){
                return json(["code"=>0,"msg"=>"该分类已存在"]);
            }
            $result=Db::name("goods_cate")->insert($list);
            if ($result){
                return json(["code"=>1,"msg"=>"添加成功"]);
            }else{
                return json(["code"=>0,"msg"=>"添加失败"]);
            }
        }
        $list=Db::name("goods_cate")->where(["pid"=>0])->select();
        $this->assign("list",$list);
        return $this->fetch("add");
    }
    /*
     * 编辑
     */
    public function edit(){
        $id=input("param.id");
        if (request()->isPost()) {
            $data["id"]=input("param.id");
            $data["cate_name"]=input("param.cate_name");
            $data["sort"]=input("param.sort");
            $result=Db::name("goods_cate")->where(["id"=>$data["id"]])->update($data);
            if ($result){
                return json(["code"=>1,"msg"=>"编辑成功"]);
            }else{
                return json(["code"=>0,"msg"=>"编辑失败"]);
            }
        }
        $find=Db::name("goods_cate")->where(["id"=>$id])->find();
        $this->assign("find",$find);
        return $this->fetch("edit");
    }

    /*
     * 删除
     */
    public function del(){
        $id=input("param.id");
        $find=Db::name("goods_cate")->where(["pid"=>$id])->find();
        if ($find){
            return json(["code"=>0,"msg"=>"该分类已经存在，不可删除"]);
        }else{
            $result=Db::name("goods_cate")->where(["id"=>$id])->delete();
            writelog("删除分类成功");
            if ($result){
                return json(["code"=>1,"msg"=>"删除成功"]);
            }else{
                return json(["code"=>0,"msg"=>"删除失败"]);
            }
        }

    }

}